package com.buaa.rental.Controller;

import com.buaa.rental.Dao.*;
import com.buaa.rental.Dao.User.Role;
import com.buaa.rental.Service.MailService;
import com.buaa.rental.Service.UserService;
import com.buaa.rental.Service.VerificationService;
import com.buaa.rental.Util.*;
import com.buaa.rental.Util.MyAnnotations.Authorization;
import com.buaa.rental.Util.MyAnnotations.CurrentUser;
import java.util.Map;
import java.util.Random;
import javax.servlet.http.Cookie;
import javax.servlet.http.*;
import javax.validation.Valid;
import javax.validation.constraints.Email;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("api/user")
public class UserController
{

	@Autowired
	private UserService userService;

	@Autowired
	private MailService mailService;
	@Autowired
	private VerificationService verificationService;

	@PostMapping(value = "getVeryCode")
	public CommonRep getVeryCode(@RequestParam("email") String email) throws Exception
	{
		Random r = new Random();
		String code = "" + ((10000000 + r.nextInt(10000000)) % 900000 + 100000);
		verificationService.updateCode(email, code);
		mailService.sendMessage("账号验证", email + "您好：\n"
				+ "请您输入验证码，" + code + "完成您的验证\n", email);

		return new CommonRep();
	}

	@RequestMapping(value = "register", method = RequestMethod.POST)
	public CommonRep register(@RequestBody @Valid User user, BindingResult res) throws CodeException
	{
		if (res.hasErrors())
		{
			throw new CodeException("101", DataFormat.bindingErrorsFormat(res));
		}
		if (user.email == null || user.psw == null || user.name == null)
		{
			throw new CodeException("101", "不能为空");
		}
		try
		{
			String very = verificationService.getCode(user.email);
			if (user.verificationCode == null || !very.equals(user.verificationCode))
			{
				throw new Exception("验证码错误");
			}
			user.role = Role.user;
			userService.register(user);

		} catch (Exception e)
		{
			throw new CodeException("102", e.getMessage());
		}
		return new CommonRep();
	}

	@RequestMapping(value = "login", method = {RequestMethod.POST})
	public CommonRep login(@RequestBody Map<String, String> req, HttpServletRequest request,
			HttpServletResponse response) throws CodeException
	{
		String email = req.get("email");
		String psw = req.get("psw");
		if (email == null || psw == null)
		{
			throw new CodeException("102", "用户名或者密码错误");
		}
		User user = userService.login(email, psw);
		if (user == null || user.id == null)
		{
			throw new CodeException("102", "用户名或者密码错误");
		}

		HttpSession session = request.getSession();
		session.setAttribute("email", email);
		session.setAttribute("psw", psw);
		session.setMaxInactiveInterval(24 * 60 * 60 * 7);
		Cookie usernameCookie = new Cookie("uid", user.id);
		usernameCookie.setMaxAge(24 * 60 * 60 * 7);
		usernameCookie.setPath("/");
		response.addCookie(usernameCookie);

		Cookie[] cookies = request.getCookies();
		if (cookies != null)
		{
			for (Cookie cookie : cookies)
			{
				if (cookie.getName().equals("JSESSIONID"))
				{
					cookie.setValue(session.getId());
					cookie.setPath("/");
					cookie.setMaxAge(24 * 60 * 60 * 7);
					response.addCookie(cookie);
				}
			}
		} else
		{
			Cookie sessionCookie = new Cookie("JSESSIONID", session.getId());
			sessionCookie.setPath("/");
			sessionCookie.setMaxAge(24 * 60 * 60 * 7);
			response.addCookie(sessionCookie);
		}

		CommonRep rep = new CommonRep();
		rep.setData(user.uid);
		return rep;
	}

	@Authorization
	@PostMapping("logout")
	public CommonRep logout(@CurrentUser User user, HttpServletRequest request,
			HttpServletResponse response)
	{
		HttpSession session = request.getSession();
		Cookie usernameCookie = new Cookie("uid", user.id);
		usernameCookie.setMaxAge(0);
		usernameCookie.setPath("/");
		response.addCookie(usernameCookie);
		Cookie sessionCookie = new Cookie("JSESSIONID", session.getId());
		sessionCookie.setPath("/");
		sessionCookie.setMaxAge(24 * 60 * 60 * 7);
		response.addCookie(sessionCookie);
		session.invalidate();
		return new CommonRep();
	}

	@Authorization
	@RequestMapping(value = "getRole", method = RequestMethod.GET)
	public CommonRep getRole(@CurrentUser User u)
	{
		CommonRep rep = new CommonRep();
		rep.setData(u.role);
		return rep;
	}

	@Authorization
	@RequestMapping(value = "getMyInfo", method = RequestMethod.GET)
	public CommonRep getMyInfo(@CurrentUser User u)
	{
		CommonRep rep = new CommonRep();
		rep.setData(u);
		return rep;
	}

	@GetMapping("getUserInfo/{uid}")
	public CommonRep getUserInfo(@PathVariable("uid") long uid)
	{
		CommonRep rep = new CommonRep();
		User u = userService.getUserByUid(uid);
		rep.setData(u);
		return rep;
	}

	@Authorization
	@PostMapping("changeUserInfo")
	public CommonRep changeUserInfo(@CurrentUser User cu, @RequestBody @Valid User user,
			BindingResult res)
			throws CodeException
	{
		if (res.hasErrors())
		{
			throw new CodeException("101", DataFormat.bindingErrorsFormat(res));
		}
		if (user.name != null)
		{
			cu.name = user.name;
		}
		if (user.age != 0)
		{
			cu.age = user.age;
		}
		if (user.province != null)
		{
			cu.province = user.province;
		}
		if (user.district != null)
		{
			cu.district = user.district;
		}
		if (user.phoneNum != null)
		{
			cu.phoneNum = user.phoneNum;
		}
		if (user.personIntro != null)
		{
			cu.personIntro = user.personIntro;
		}
		if (user.avatar != null)
		{
			cu.avatar = user.avatar;
		}

		userService.updateUser(cu);
		return new CommonRep();
	}

	@Authorization
	@PostMapping("changePsw")
	public CommonRep changePsw(@CurrentUser User user, @RequestBody Map<String, String> req)
			throws CodeException
	{
		String oldPsw = req.get("oldPsw");
		String psw = req.get("psw");
		if (oldPsw == null || psw == null)
		{
			throw new CodeException("102", "密码不能为空");
		}
		if (user.psw != oldPsw)
		{
			throw new CodeException("102", "密码错误");
		}
		user.psw = psw;
		userService.updateUser(user);
		return new CommonRep();
	}

}
